﻿using System;
using System.IO;

namespace CodeLibrary.NativeMethods.Utils
{
    public static class Shell32Utils
    {
        public static System.Drawing.Icon ExtractIcon(string fileName)
        {
            try
            {
                if (File.Exists(fileName) || Directory.Exists(fileName))
                {
                    IntPtr hIcon = Native.NativeMethods.ExtractIconA(
                        IntPtr.Zero, fileName, 0);
                    return hIcon.Equals(IntPtr.Zero)
                               ? ExtractAssociatedIcon(fileName)
                               : System.Drawing.Icon.FromHandle(hIcon);
                }
            }
            catch (ArgumentException)
            {
                return null;
            }
            return null;
        }

        public static System.Drawing.Icon ExtractAssociatedIcon(string fileName)
        {
            if (File.Exists(fileName) || Directory.Exists(fileName))
            {
                int i = 0;
                IntPtr hIcon = Native.NativeMethods.ExtractAssociatedIconA(
                    IntPtr.Zero, fileName, ref i);
                if (!hIcon.Equals(IntPtr.Zero))
                    return System.Drawing.Icon.FromHandle(hIcon);
            }
            return null;
        }
    }
}
